package models

import (
	"fmt"
	"gin_cli/conf"
	"gin_cli/pkg/logging"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

var Db *gorm.DB

func init() {
	var err error
	user := conf.DatabaseConf.User
	password := conf.DatabaseConf.Password
	host := conf.DatabaseConf.Host
	dbName := conf.DatabaseConf.Name
	dbType := conf.DatabaseConf.Type

	Db, err = gorm.Open(dbType, fmt.Sprintf(
		"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		user,
		password,
		host,
		dbName,
	))
	// fmt.Println("dbName", dbName)
	//defer Db.Close()
	// Db.DB.Ping()
	if err != nil {
		logging.Error("数据库连接", err)
	}

	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return defaultTableName
	}

	Db.LogMode(true)
	Db.SingularTable(true)
	Db.DB().SetMaxIdleConns(10)
	Db.DB().SetMaxOpenConns(100)
	Db.DB().SetConnMaxLifetime(60 * time.Second)
}

func CloseDB() {
	defer Db.Close()
}

func ParsePagination(result *gorm.DB, pagination map[string]interface{}) *gorm.DB {
	_, ok1 := pagination["current"]
	_, ok2 := pagination["pageSize"]
	if ok1 && ok2 {
		result = result.
			Limit(pagination["pageSize"]).
			Offset((pagination["current"].(int) - 1) * pagination["pageSize"].(int))
	}
	if v, ok := pagination["type"]; ok {
		result = result.Where("type in (?)", v)
	}

	if v, ok := pagination["sorts"]; ok {
		list := v.([]string)
		for _, value := range list {
			result = result.Order(value)
		}
	}

	return result
}

func ParseWhere(result *gorm.DB, where map[string]interface{}) *gorm.DB {
	for k, v := range where {
		switch v.(type) {
		case string:
			result = result.Where(k+" = ?", v)
		case int:
			result = result.Where(k+" = ?", v)
		case []string:
			result = result.Where(k+" in (?)", v)
		case []int:
			result = result.Where(k+" in (?)", v)
		default:

		}
	}
	return result
}
